<template>
  <el-dialog
    v-model="dialogModel"
    width="80%"
    :fullscreen="isFullscreen"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <template #header v-if="dialogModel">
      <span class="el-dialog__title">{{ title + '编写' }}</span>
      <div class="header-icon">
        <el-icon v-if="!isFullscreen" @click="isFullscreen = true"><FullScreen /></el-icon>
        <svg-icon v-else @click="isFullscreen = false" icon-class="unfull" />
      </div>
    </template>
    <!-- <el-row>
      脚本语言:
      <el-radio v-model="editScript.typ" label="js" />
    </el-row> -->
    <el-row v-if="dialogModel" justify="space-between" class="row-box" v-loading="loading">
      <el-col :span="16">
        {{ title }}：
        <div v-if="editScript.typ == 'js'">new (function () {</div>
        <code-editor v-model:code="editScript.script" />
        <div v-if="editScript.typ == 'js'">})()</div>
      </el-col>
      <el-col :span="7" class="right-box">
        测试数据：
        <div style="height: 200px; overflow: auto">
          <code-editor v-model:code="testDataScript.script" />
        </div>
        <el-row style="padding: 5px 5px">
          测试结果：
          <el-button v-if="type === 'change'" size="small" type="primary" @click="execTest('decode')">解码测试</el-button>
          <el-button v-if="type === 'change'" size="small" type="primary" @click="execTest('encode')">编码测试</el-button>
          <el-button v-if="type === 'communication'" size="small" type="primary" @click="execTest()">测试</el-button>
        </el-row>
        <div>
          <el-input type="textarea" v-model="testDataScript.testResult" :readonly="true" :rows="7" />
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <el-button :loading="loading" @click="dialogModel = false">关闭</el-button>
      <el-button :loading="loading" @click="handleSave" type="primary">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { propTypes } from '@/utils/propTypes'
import { getConverterScript, editConverterScript } from '@/api/eiot/communication/convertors.api'
import { getComponentDetail, saveComponentScript } from '@/api/eiot/communication/component.api'

import CodeEditor from '@/components/CodeEditor/index.vue'

const dialogModel = ref(false)
const props = defineProps({
  title: propTypes.string.def('标题'),
  type: propTypes.string.def('change'), // 转换：change 通讯：communication
})
const isFullscreen = ref(false)
const editScript = reactive<any>({
  id: '',
  typ: 'js',
  script: '',
})
const data = ref()
const loading = ref(false)
const testDataScript = reactive({
  script: '{}',
  testResult: ''
})
// 执行操作 decode: 解码 encode： 编码
const execTest = (type?: 'decode' | 'encode') => {
  try {
    localStorage.setItem(
      'testDataScript_' + editScript.id,
      testDataScript.script || '{}'
    )

    var script = 'new (function (){' + editScript.script + '})()'
    var coder = eval(script)
    var testData = eval(
      '(function(){return ' + testDataScript.script + '})()'
    )
    if (type) {
      testDataScript.testResult = JSON.stringify(coder[type](testData))
    } else {
      testDataScript.testResult = JSON.stringify(
        coder.onReceive(testData.head, testData.type, testData.payload)
      )
    }
  } catch (err) {
    testDataScript.testResult = err as string
  }
}

// 打开弹窗
const openDialog = (row: any) => {
  dialogModel.value = true
  editScript.id = row.id
  loading.value = true
  const getDetailFun = props.type === 'communication' ? getComponentDetail : getConverterScript
  getDetailFun(row.id).then(res => {
    if (res.code === 200 && res.data.script) {
      editScript.script = res.data.script
      data.value = res.data
    }
  }).finally(() => {
    loading.value = false
  })
  editScript.script = '' ||
  `this.decode = function (msg) {
    return null
  }
this.encode = function (service,device) {
  return null
}
  `
  testDataScript.script =
          localStorage.getItem('testDataScript2_' + row.id) || '{}'
}
// 保存
const handleSave = () => {
  if (!editScript.script) return ElMessage.error('请输入转换脚本!')
  loading.value = true
  const editFun = props.type === 'communication' ? saveComponentScript : editConverterScript
  const content = {
  ...data.value,
  ...editScript
  }
  editFun(content).then(() => {
    ElMessage.success('保存成功')
    dialogModel.value = false
  }).finally(() => {
    loading.value = false
  })
}
defineExpose({
  openDialog,
})
</script>

<style lang="scss" scoped>
.row-box {
  position: relative;
  .right-box {
    position: sticky;
    top: 0;
    min-height: 300px;
  }
}
.header-icon {
  position: absolute;
  top: 22px;
  right: 50px;
  color: #909399;
  cursor: pointer;
}
</style>
